<template>
  <div class="app-container">
    <el-row>
      <!-- 搜索区域 -->
      <el-card style="margin:0 0 5px 5px" v-show="showSearch">
        <el-form ref="queryForm" :inline="true" :model="queryData">
          <el-form-item label="模型标识" prop="Q_modelKey_S_LK">
            <el-input v-model="queryData.Q_modelKey_S_LK" placeholder="模型标识" />
          </el-form-item>
          <el-form-item label="模型名称" prop="Q_modelName_S_LK">
            <el-input v-model="queryData.Q_modelName_S_LK" placeholder="模型名称" />
          </el-form-item>
          <el-form-item label="流程分类" prop="Q_category_S_EQ">
            <el-select v-model="queryData.Q_category_S_EQ" placeholder="流程分类">
              <el-option label="全部" value="" />
              <el-option
                v-for="item in optionOfCategory"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="fr p-r-10">
            <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button class="filter-item m-l-10" type="info" round icon="el-icon-refresh" @click="handleClear">
              清空
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- table区域 -->
      <el-card class="m-l-5">
        <el-row :gutter="10" class="m-b-5">
          <el-col :span="1.5">
            <el-button v-permission="['flowable:model:add']" size="mini" plain type="primary" icon="el-icon-plus" @click="handleEdit()">
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-permission="['flowable:model:delete']" v-if="selectionData.length > 0" size="mini" plain type="danger" icon="el-icon-delete" @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <table-toolbar :showSearch.sync="showSearch" @refresh="getTableData" />
        </el-row>
        <el-table
          ref="modelTable"
          v-loading="tableLoading"
          row-key="modelId"
          :data="tableData"
          element-loading-text="加载中"
          border
          fit
          highlight-current-row
          show-overflow-tooltip
          height="100px"
          v-el-height-adaptive-table="{bottomOffset: 110}"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column align="center" label="模型标识" prop="modelKey" sortable show-overflow-tooltip />
          <el-table-column align="center" label="模型名称" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-button type="text" @click="handleEdit(scope.row)">
                <span>{{ scope.row.modelName }}</span>
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="流程分类" prop="category" sortable width="120">
            <template slot-scope="scope">
              <el-tag :type="getDictType('category', scope.row.category)" v-text="getDictValue('category', scope.row.category)" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="模型版本" width="90">
            <template slot-scope="scope">
              <el-tag size="medium" >v{{ scope.row.version }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="描述" prop="description" show-overflow-tooltip />
          <el-table-column align="center" label="创建时间" prop="createTime" width="180" />
          <el-table-column align="center" label="操作" width="180" fixed="right">
            <template slot-scope="scope">
              <el-link v-permission="['flowable:model:edit']"
                       size="mini"
                       type="primary"
                       icon="el-icon-brush"
                       class="m-r-5"
                       @click="handleDesigner(scope.row)">
                设计
              </el-link>
              <el-link v-permission="['flowable:model:edit']"
                       size="mini"
                       type="danger"
                       icon="el-icon-video-play"
                       class="m-r-5"
                       @click="handleDeploy(scope.row.modelId)">
                部署
              </el-link>
              <el-dropdown>
                <span class="el-dropdown-link" style="font-size: smaller">
                  <i class="el-icon-d-arrow-right el-icon--right" />更多
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-permission="['flowable:model:view']">
                    <el-link icon="el-icon-view" @click="handleProcessView(scope.row.modelId)">流程图</el-link>
                  </el-dropdown-item>
                  <el-dropdown-item v-permission="['flowable:model:view']">
                    <el-link type="warning" icon="el-icon-price-tag" @click="handleHistory(scope.row.modelKey)">历史</el-link>
                  </el-dropdown-item>
                  <el-dropdown-item v-permission="['flowable:model:view']">
                    <el-link type="success" icon="el-icon-view" @click="handleEdit(scope.row)">修改</el-link>
                  </el-dropdown-item>
                  <el-dropdown-item v-permission="['flowable:model:delete']">
                    <el-link type="danger" icon="el-icon-delete" @click="handleDelete(scope.row.modelId)">删除</el-link>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData" />
      </el-card>
    </el-row>

    <model-dialog v-if="openModelDialog" ref="modelForm" @confirmForm="handleFilter" />
    <model-history-dialog v-if="openHistoryDialog" ref="historyTable" />

    <!-- 流程图 -->
    <el-drawer :title="processView.title" :visible.sync="processView.open" :modal="false" direction="rtl" size="60%" append-to-body>
      <process-viewer :key="`designer-${processView.index}`" :xml="processView.xmlData" :style="{height: '600px'}" />
    </el-drawer>

    <!-- 设计器 -->
    <el-dialog :title="designerData.title" :visible.sync="designerData.open" fullscreen append-to-body>
      <process-designer
        :key="designerData.open"
        style="border:1px solid rgba(0, 0, 0, 0.1);"
        ref="modelDesigner"
        v-loading="designerData.loading"
        :bpmnXml="designerData.bpmnXml"
        :designerForm="designerData.form"
        @save="onSaveDesigner"
      />
    </el-dialog>
  </div>
</template>

<script>
import { categoryGroup, modelTable, modelXml, modelSave, modelDeploy, modelDelete } from '@/api/tool/workflow'
import ProcessViewer from '@/components/ProcessViewer'
import ProcessDesigner from '@/components/ProcessDesigner'
import ModelDialog from './form/dialog'
import ModelHistoryDialog from './table/history'

export default {
  components: {
    ProcessViewer,
    ProcessDesigner,
    ModelDialog,
    ModelHistoryDialog
  },
  data() {
    return {
      showSearch: true,
      queryData: {
        Q_modelKey_S_LK: undefined,
        Q_modelName_S_LK: undefined,
        Q_category_S_EQ: undefined
      },
      tableLoading: false,
      tableData: [],
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      },
      selectionData: [],
      optionOfCategory: [],
      openModelDialog: false,
      openHistoryDialog: false,
      processView: {
        title: '',
        open: false,
        index: undefined,
        xmlData: '',
      },
      designerData: {
        title: '',
        open: false,
        loading: false,
        bpmnXml: '',
        modelId: null,
        form: {
          processName: null,
          processKey: null,
          category: null
        }
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // 加载下拉菜单
      this.getDictData()
      this.getTableData()
    },
    getDictData() {
      categoryGroup().then(response => {
        this.optionOfCategory = response
      }).catch(e => {})
    },
    getDictType(property, value) {
      return this.$api.getDictElement(this.optionOfCategory, value)[0]
    },
    getDictValue(property, value) {
      return this.$api.getDictElement(this.optionOfCategory, value)[1]
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getTableData()
    },
    handleClear() {
      this.$refs.queryForm.resetFields()
      this.getTableData()
    },
    getTableData() {
      const query = Object.assign(this.tableQuery, this.queryData)
      this.tableLoading = true
      modelTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
        this.$refs.modelTable.bodyWrapper.scrollTop = 0
      }).catch(e => {
        this.tableLoading = false
      })
    },
    sortChange(data) {
      const { prop, order } = data
      this.tableQuery.sort = prop
      if (order === 'ascending') {
        this.tableQuery.order = 'asc'
      } else {
        this.tableQuery.order = 'desc'
      }
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.selectionData = val
    },
    handleEdit(row) {
      this.openModelDialog = true
      this.$nextTick(() => {
        this.$refs.modelForm.init(row)
      })
    },
    handleProcessView(modelId) {
      this.processView.title = '流程图'
      this.processView.index = modelId
      modelXml(modelId).then(response => {
        this.processView.xmlData = response.param
      })
      this.processView.open = true
    },
    handleHistory(modelKey) {
      this.openHistoryDialog = true
      this.$nextTick(() => {
        this.$refs.historyTable.init(modelKey)
      })
    },
    handleDesigner(row) {
      this.designerData.title = '流程设计 - ' + row.modelName
      this.designerData.modelId = row.modelId
      this.designerData.form = {
        processName: row.modelName,
        processKey: row.modelKey,
        category: row.category
      }
      if (row.modelId) {
        this.designerData.loading = true
        modelXml(row.modelId).then(response => {
          this.designerData.bpmnXml = response.param || ''
          this.designerData.loading = false
          this.designerData.open = true
        })
      }
    },
    onSaveDesigner(bpmnXml) {
      this.bpmnXml = bpmnXml
      let dataBody = {
        modelId: this.designerData.modelId,
        bpmnXml: this.bpmnXml,
        category: this.designerData.form.category
      }

      this.$confirm("是否将此模型保存为新版本？", "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: '是',
        cancelButtonText: '否'
      }).then(() => {
        this.confirmSave(dataBody, true)
      }).catch(action => {
        if (action === 'cancel') {
          this.confirmSave(dataBody, false)
        }
      })
    },
    handleDeploy(modelId) {
      this.tableLoading = true
      modelDeploy(modelId).then(response => {
        this.$modal.msgSuccess(response.msg)
      }).finally(() => this.tableLoading = false)
    },
    confirmSave(body, newVersion) {
      this.designerData.loading = true
      const model = Object.assign(body, { newVersion: newVersion })
      modelSave(model).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.designerData.open = false
        this.handleFilter()
      }).catch(response => {
        this.$modal.msgError(response.msg)
      }).finally(() => this.designerData.loading = false)
    },
    handleDelete(id) {
      const ids = this.selectionData.map(function(model, index) {
        return model.modelId
      }).join(',')

      id = id || ids
      if (!id || id.length === 0) {
        this.$modal.msgWarning('请先选中数据项')
        return
      }

      this.$confirm('是否删除所选模型?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        modelDelete({ ids: id }).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response.msg)
        })
      })
    }
  }
}
</script>
